<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               :upload-after="uploadAfter"
               :upload-before="uploadBefore"
               :before-close="beforeClose"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.goods_delete"
                   @click="handleDelete">删 除
        </el-button>
        <el-button type="success"
                   size="small"
                   plain
                   @click="handleChangeStatus(3)">上架
        </el-button>
        <el-button type="warning"
                   size="small"
                   plain
                   @click="handleChangeStatus(2)">下架
        </el-button>
      </template>
      <template slot-scope="{row}"
                slot="categoryId">
        <span v-if="row.categoryName.split(',').length > 0 && row.categoryName !== ''"
              v-for="(name, i) in row.categoryName.split(',')" :key="i">
          <el-tag
            size="small"
            type="success"
          >{{name}}</el-tag>&nbsp;
        </span>
      </template>
      <template slot-scope="{row}"
                slot="createUser">
        <span>{{ row.createUserName }}</span>
      </template>
      <template slot-scope="{row}"
                slot="status">
        <el-tag
          v-if="row.status === goodsStatus[0].value"
          size="small"
          type="info"
        >{{ row.statusName }}</el-tag>
        <el-tag
          v-else-if="row.status === goodsStatus[1].value"
          size="small"
          type="danger"
        >{{ row.statusName }}</el-tag>
        <el-tag
          v-else-if="row.status === goodsStatus[2].value"
          size="small"
          type="success"
        >{{ row.statusName }}</el-tag>
      </template>
      <template slot-scope="{row}"
                slot="summary">
        <avue-text-ellipsis :text="row.summary" :height="50">
          <small slot="more">...</small>
        </avue-text-ellipsis>
      </template>
      <template slot-scope="{row}"
                slot="pictureUrl">
        <div class="avue-crud__img" v-if="row.pictureUrl.split(',').length > 0 && row.pictureUrl !== ''">
          <img :src="row.pictureUrl.split(',')[0]"/>
        </div>
      </template>
      <template slot-scope="{row}" slot="menu">
        <el-button
          icon="el-icon-setting"
          type="primary"
          size="small"
          @click.stop="handleStyle(row)"
        >规格
        </el-button>
<!--        <el-button-->
<!--          icon="el-icon-goods"-->
<!--          type="primary"-->
<!--          size="small"-->
<!--          @click.stop="handlePackage(row)"-->
<!--        >套餐-->
<!--        </el-button>-->
        <el-button
          v-if="row.status === 3 || website.adminRoles.includes(userInfo.authority)"
          icon="el-icon-goods"
          type="primary"
          size="small"
          @click.stop="handleView(row)"
        >预览
        </el-button>
        <el-button
          v-if="website.adminRoles.includes(userInfo.authority)"
          icon="el-icon-unlock"
          type="warning"
          size="small"
          @click.stop="handleReView(row)"
        >上架
        </el-button>
      </template>
    </avue-crud>
    <el-dialog
      title="商品规格"
      width="80%"
      @close="dialogVisible=false; styleTypeList=[]"
      :visible.sync="dialogVisible">
      <basic-container>
        <div :key="index" v-for="(styleType, index) in styleTypeList" style="margin-bottom: 10px">
          <el-input
            style="display: inline-block; width: 20%"
            v-model="styleType.value"
          ></el-input>
          <el-button
            style="display: inline-block; margin-left: 10px;"
            type="danger"
            size="small" @click="removeStyleType(index)">删 除</el-button>
        </div>
        <el-button type="primary" size="small" @click="addStyleType">添加商品规格</el-button>
      </basic-container>
      <basic-container>
        <el-table
          :data="dataStyle"
          style="width: 100%">
          <el-table-column
            prop="pictureUrl"
            label="图片"
            width="180">
            <template slot-scope="scope">
              <el-upload
                class="avatar-uploader"
                action="/api/blade-resource/oss/endpoint/put-file"
                :headers="uploadHeaders"
                :show-file-list="false"
                :on-success="onUploadSuccess">
                <img @click="handleUploadRowImage(scope.$index)" width="100px" height="100px" v-if="scope.row.pictureUrl" :src="scope.row.pictureUrl" class="avatar">
                <el-button plain v-else size="small" type="primary" @click="handleUploadRowImage(scope.$index)">上传图片</el-button>
              </el-upload>
            </template>
          </el-table-column>
          <el-table-column
            prop="value"
            label="规格">
            <template slot-scope="scope">
              <div v-if="scope.row.value && Object.keys(scope.row.value).length !== 0" @click="handleStyleNameInput(scope.$index)">
                <el-tag :key="i" style="margin-right: 5px" v-for="(item, i) in scope.row.value" class="item">{{item}}</el-tag>
              </div>
              <el-button plain v-else size="small" type="primary" @click="handleStyleNameInput(scope.$index)">编辑规格</el-button>
            </template>
          </el-table-column>
          <el-table-column
            prop="price"
            width="120"
            label="售价">
            <template slot-scope="scope">
              <el-input type="number" class="item" v-model="scope.row.price">
                <i slot="prefix" class="el-input__icon">￥&nbsp;</i>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column
            prop="originalPrice"
            width="120"
            label="原价">
            <template slot-scope="scope">
              <el-input type="number" class="item" v-model="scope.row.originalPrice">
                <i slot="prefix" class="el-input__icon">￥&nbsp;</i>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column
            prop="costPrice"
            width="120"
            label="成本价">
            <template slot-scope="scope">
              <el-input type="number" class="item" v-model="scope.row.costPrice">
                <i slot="prefix" class="el-input__icon">￥&nbsp;</i>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column
            prop="inStock"
            width="120"
            label="库存">
            <template slot-scope="scope">
              <el-input type="number" class="item" v-model="scope.row.inStock"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            prop="barCode"
            width="180"
            label="条码">
            <template slot-scope="scope">
              <el-input class="item" v-model="scope.row.barCode"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            width="180"
            label="操作">
            <template slot-scope="scope">
              <el-button type="danger" size="small" @click="removeTypeRow(scope.$index)">删 除</el-button>
              <el-button size="small" @click="copyTypeRow(scope.$index)">复 制</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-button type="primary" size="small" @click="addStyle">添 加</el-button>
      </basic-container>

      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible=false; innerForm=[]; styleTypeList=[]">取 消</el-button>
        <el-button size="small" type="primary" @click="submitType">提 交</el-button>
      </span>

      <el-dialog
        width="40%"
        title="规格"
        :visible.sync="innerVisible"
        append-to-body>

        <div :key="i" v-for="(type, i) in styleTypeList" style="margin-bottom: 10px; margin-left: 10%">
          <div style="display: inline-block; width: 10%">
            {{ type.value }}
          </div>
          <el-input
            style="display: inline-block; margin-left: 10px; width: 60%"
            v-model="innerForm[type.value]"
            class="item" />
        </div>

        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="innerVisible = false; innerForm={}">取 消</el-button>
          <el-button size="small" type="primary" @click="submitInnerForm">确 定</el-button>
        </div>
      </el-dialog>
    </el-dialog>
    <el-dialog
      title="商品套餐"
      width="70%"
      @close="dialogPackageVisible=false; goodsPackageList=[]"
      :visible.sync="dialogPackageVisible">
      <basic-container>
        <el-table
          :data="goodsPackageList"
          style="width: 100%">
          <el-table-column
            prop="pictureUrl"
            label="图片"
            width="180">
            <template slot-scope="scope">
              <el-upload
                class="avatar-uploader"
                action="/api/blade-resource/oss/endpoint/put-file"
                :headers="uploadHeaders"
                :show-file-list="false"
                :on-success="onUploadPackageSuccess">
                <img @click="handleUploadRowPackageImage(scope.$index)" width="100px" height="100px" v-if="scope.row.pictureUrl" :src="scope.row.pictureUrl" class="avatar">
                <el-button plain v-else size="small" type="primary" @click="handleUploadRowPackageImage(scope.$index)">上传图片</el-button>
              </el-upload>
            </template>
          </el-table-column>
          <el-table-column
            prop="name"
            width="400"
            label="套餐名">
            <template slot-scope="scope">
              <el-input class="item" v-model="scope.row.name" placeholder="请填写套餐名">
              </el-input>
            </template>
          </el-table-column>
          <el-table-column
            prop="goodsCount"
            width="180"
            label="商品数量">
            <template slot-scope="scope">
              <el-input type="number" class="item" v-model="scope.row.goodsCount" placeholder="请填写商品数量"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            prop="price"
            width="180"
            label="套餐价格">
            <template slot-scope="scope">
              <el-input type="number" class="item" v-model="scope.row.price" placeholder="请填写套餐价格"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            width="180"
            label="操作">
            <template slot-scope="scope">
              <el-button type="danger" size="small" @click="removePackageRow(scope.$index)">删 除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-button type="primary" size="small" @click="addPackage">添 加</el-button>
      </basic-container>

      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogPackageVisible=false">取 消</el-button>
        <el-button size="small" type="primary" @click="submitPackage">提 交</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="商品审核"
      width="40%"
      @close="dialogReviewVisible=false"
      :visible.sync="dialogReviewVisible">
      <basic-container style="font-weight: bold; font-size: 15px;">
        <div style="margin-bottom: 15px">商品名称: {{ this.form.name }}</div>
        <div style="margin-bottom: 15px">发布人: {{ this.form.createUserName }}</div>
        <div>发布时间: {{ this.form.createTime }}</div>
      </basic-container>

      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="info" @click="dialogReviewVisible=false">取 消</el-button>
        <el-button size="small" type="success" @click="goodsVerified">上 架</el-button>
        <el-button size="small" type="danger" @click="goodsReject">下 架</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
import {getList, getDetail, add, update, remove, statusChange} from "@/api/goods/goods";
  import {getSelect as getCategoryList} from "@/api/goods/goods_category";
  import {getList as getStyleList, submit} from "@/api/goods/goods_style";
  import {getList as getPackageList, submit as submitPackage} from "@/api/goods/goods_package";
  import {getList as getDomainList} from "@/api/user/user_domain";
  import {mapGetters} from "vuex";
  import {Base64} from "js-base64";
  import website from "@/config/website";
  import {getToken} from "@/util/auth";
  import {putFiles} from "@/api/other/resource";

  const DIC = {
    IS_ONLY_HOME: [{
      label: '否',
      value: 2
    }, {
      label: '是',
      value: 1
    }]
  }
  export default {
    data() {
      return {
        goodsStatus: [
          {
            value: 1,
            name: '待上架'
          },
          {
            value: 2,
            name: '下架'
          },
          {
            value: 3,
            name: '上架'
          }
        ],
        dialogReviewVisible: false,
        dialogViewVisible: false,
        dialogPackageVisible: false,
        goodsPackageList: [],
        packageLoading: false,
        packageSelectedIndex: 0,
        innerForm: {},
        innerVisible: false,
        styleInputIndex: 0,
        styleTypeList: [],
        currentTypeIndex: 0,
        uploadHeaders: {
          Authorization: `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`,
          "Blade-Auth": 'bearer ' + getToken()
        },
        dialogVisible: false,
        styleLoading: false,
        dataStyle: [],
        goodsId: 0,
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height: 'auto',
          calcHeight: 210,
          searchShow: true,
          searchMenuSpan: 6,
          tip: false,
          border: true,
          index: false,
          menuWidth: 400,
          menuType: 'icon',
          viewBtn: false,
          delBtn: false,
          selection: true,
          column: [
            {
              label: "商品名称",
              prop: "name",
              rules: [{
                required: true,
                message: "请输入商品名称",
                trigger: "blur"
              }],
              search: true
            },
            {
              label: "分类",
              prop: "categoryId",
              multiple: true,
              type: "select",
              dicData: [],
              props: {
                label: "name",
                value: "id"
              },
              slot: true,
              rules: [{
                required: true,
                message: "请选择类型",
                trigger: "blur"
              }]
            },
            {
              label: "商户",
              prop: "createUser",
              slot: true,
              search: true,
              display: false
            },
            {
              label: "发布时间",
              prop: "createTime",
              display: false
            },
            {
              label: "销量",
              prop: "sell",
              type: "number",
              editDisabled: true,
              addDisabled: true,
              hide: true
            },
            {
              label: "状态",
              prop: "status",
              display: false,
              slot: true
            },
            {
              label: "显示销量",
              prop: "displaySell",
              type: "number",
              hide: true
            },
            {
              label: "摘要",
              prop: "summary",
              slot: true,
              hide: true
            },
            {
              label: "显示价格",
              prop: "displayPrice",
              type: "number",
              rules: [{
                required: true,
                message: "请输入显示价格",
                trigger: "click"
              }]
            },
            {
              label: "排序",
              prop: "sort",
              type: "number",
              hide: true
            },
            {
              label: "仅限宅配",
              prop: "isOnlyHome",
              type: "switch",
              dicData: DIC.IS_ONLY_HOME,
              value: DIC.IS_ONLY_HOME[0].value,
              rules: [{
                required: true,
                message: "请选择是否仅限宅配",
                trigger: "click"
              }],
              hide: true,
              display: false
            },
            {
              label: "封面/图片",
              prop: "pictureUrl",
              dataType: 'string',
              type: 'upload',
              multiple: true,
              slot: true,
              span: 24,
              listType: 'picture-card',
              propsHttp: {
                res: 'data',
                url: 'link',
                name: 'originalName'
              },
              onRemove:(file, fileList)=>{
                this.temPictureNameArray = fileList.map(item => {
                  return item.url
                })
              },
              limit: 9,
              tip: '只能上传图片(jpg/png/gif...)文件，不建议图片过大, 限制9张图片, 第一张图为封面',
              action: '/api/blade-resource/oss/endpoint/put-file'
            },
            {
              label: "描述",
              prop: "description",
              type: "ueditor",
              component: 'avue-ueditor',
              action: "/api/blade-resource/oss/endpoint/put-file",
              propsHttp: {
                res: "data",
                url: "link"
              },
              options: {
                action: "/api/blade-resource/oss/endpoint/put-file",
                customConfig: {
                  uploadImgMaxSize: 30 * 1024 *1024
                },
                props: {
                  res: "data",
                  url: "link"
                },
              },
              span: 24,
              hide: true
            }
          ]
        },
        data: [],
        userDomainList: [],
        temPictureNameArray: [],
        picTimer: null
      };
    },
    computed: {
      ...mapGetters(["website", "userInfo", "permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.goods_add, false),
          viewBtn: this.vaildData(this.permission.goods_view, false),
          delBtn: this.vaildData(this.permission.goods_delete, false),
          editBtn: this.vaildData(this.permission.goods_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    mounted () {
      const createUserColumn = this.option.column.find(item => item.prop === 'createUser')
      createUserColumn.hide = website.superAdminRoles !== this.userInfo.authority
      createUserColumn.search = website.superAdminRoles === this.userInfo.authority

      const column = this.option.column.find(item => item.prop === 'description')
      column.options.customConfig.customUploadImg = async (files, insert) => {
        let param = new FormData()
        for(let i=0; i<files.length; i++){
          param.append("files",files[i]);
        }
        await putFiles(param).then((res) => {
          res.data.data.map(item => {
            insert(item.link)
          })
        }, error => {
          window.console.log(error);
        });
      }
    },
    methods: {
      setPicTimer() {
        if(this.picTimer == null) {
          this.picTimer = setInterval( () => {
            // 上传后更新无效，所以在这里重新赋值
            this.form.pictureUrl = this.temPictureNameArray.join(',')
            console.log('...')
          }, 500)
        }
      },
      cleanPicTimer() {
        clearInterval(this.picTimer)
        this.picTimer = null
        this.temPictureNameArray = []
      },
      beforeClose(done) {
        this.cleanPicTimer()
        done()
      },
      uploadBefore(file, done) {
        this.temPictureNameArray.push(file.name)
        done()
      },
      uploadAfter(res, done, loading) {
        this.temPictureNameArray.forEach((item, index) => {
          if (item === res.originalName) {
            this.temPictureNameArray[index] = res.link
          }
        })
        // 这里更新好像无效
        this.form.pictureUrl = this.temPictureNameArray.join(',')
        done()
      },
      goodsVerified() {
        update({id: this.goodsId, status: this.goodsStatus[2].value}).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
        });
        this.dialogReviewVisible = false
      },
      goodsReject() {
        update({id: this.goodsId, status: this.goodsStatus[1].value}).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
        });
        this.dialogReviewVisible = false
      },
      handleChangeStatus(status) {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm(`确定将选择数据${status === 3 ? '上架' : '下架'}?`, {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return statusChange(this.ids, status);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      handleReView(row) {
        this.dialogReviewVisible = true
        this.goodsId = row.id;
        this.onLoadReview()
      },
      onLoadReview() {
        getDetail(this.goodsId).then(res => {
          this.form = res.data.data;
        });
      },
      handleView(row) {
        this.copyText = `${window.location.origin.includes('localhost') ? website.h5DomainDev : website.h5Domain}/#/pages/goods/goods?id=${row.id}`
        window.open(this.copyText, '_blank')
      },
      submitInnerForm() {
        if (Object.keys(this.innerForm).length === 0) {
          this.$message.warning("请填写规格信息!");
          return;
        }

        if (Object.keys(this.innerForm).length !== this.styleTypeList.length) {
          this.$message.warning("还有规格信息未填写!");
          return;
        }

        this.innerForm = Object.assign({}, this.innerForm) //强制转为对象, 防止数据为空
        this.$set(this.dataStyle[this.styleInputIndex], 'value', this.innerForm)
        this.$forceUpdate();
        this.innerVisible = false
        this.innerForm = {}
      },
      handleStyleNameInput(inputIndex) {
        if (this.styleTypeList.length <= 0) {
          this.$message.warning("请先添加规格类型!");
          return;
        }
        this.styleInputIndex = inputIndex
        this.innerVisible = true
        if (this.dataStyle[inputIndex].value && this.dataStyle[inputIndex].value !== '') {
          this.innerForm = this.dataStyle[inputIndex].value
        }
      },
      onUploadSuccess(res) {
        this.$set(this.dataStyle[this.currentTypeIndex], 'pictureUrl', res.data.link)
        this.$forceUpdate();
      },
      handleUploadRowImage(index) {
        this.currentTypeIndex = index
      },
      removeTypeRow(index) {
        this.dataStyle.splice(index, 1)
      },
      // 复制商品规格
      copyTypeRow(index) {
        const style = JSON.parse(JSON.stringify(this.dataStyle[index]))
        delete style.id
        this.dataStyle.push(style)
      },
      addStyleType() {
        this.styleTypeList.push({
          value: ''
        })
      },
      changeDataStyleList() {
        this.dataStyle.map((style, index) => {
          const styleValue = style.value
          this.styleTypeList.map((styleType) => {
            if (!Object.keys(styleValue).includes(styleType.value)) {
              styleValue[styleType.value] = 'default'
              this.$set(this.dataStyle[index], 'value', styleValue)
              this.$forceUpdate();
            }
          })

          const styleTypeKeyList = this.styleTypeList.map(styleType => styleType.value)
          Object.keys(styleValue).map(styleKey => {
            if (!styleTypeKeyList.includes(styleKey)) {
              delete styleValue[styleKey]
              this.$set(this.dataStyle[index], 'value', styleValue)
              this.$forceUpdate();
            }
          })
        })
      },
      addPackage() {
        this.goodsPackageList.push({
          price: 0,
          goodsCount: 0
        })
      },
      removePackageRow(index) {
        this.goodsPackageList.splice(index, 1)
      },
      removeStyleType(index) {
        this.styleTypeList.splice(index, 1)
        this.changeDataStyleList()
      },
      addStyle() {
        this.dataStyle.push({
          goodsId: this.goodsId,
          inStock: 999,
          costPrice: 0,
          price: 0,
          originalPrice: 0
        })
      },
      submitType() {
        const dataList = JSON.parse(JSON.stringify(this.dataStyle))
        submit(dataList, this.goodsId).then(() => {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
        });
        this.dialogVisible = false
      },
      onLoadStyle(page, params = {}) {
        this.styleLoading = true;
        const values = {
          ...params,
          goodsId: this.goodsId,
        };
        getStyleList(
          1,
          100,
          values
        ).then((res) => {
          const data = res.data.data;
          this.dataStyle = data.records;
          this.dataStyle.forEach(style => {
            style.value = JSON.parse(style.value)

            Object.keys(style.value).map((key) => {
              if (this.styleTypeList.length === 0) {
                this.styleTypeList.push({
                  value: key
                })
              } else {
                const styleTypeValues = this.styleTypeList.map(styleType => {return styleType.value})
                if (!styleTypeValues.includes(key)) {
                  this.styleTypeList.push({
                    value: key
                  })
                }
              }
            })
          })
          this.styleLoading = false;
        });
      },
      handleStyle(row) {
        this.dialogVisible = true
        this.goodsId = row.id;
        this.onLoadStyle()
      },

      // 套餐
      onUploadPackageSuccess(res) {
        this.$set(this.goodsPackageList[this.packageSelectedIndex], 'pictureUrl', res.data.link)
        this.$forceUpdate();
      },
      handleUploadRowPackageImage(index) {
        this.packageSelectedIndex = index
      },
      handlePackage(row) {
        this.dialogPackageVisible = true
        this.goodsId = row.id;
        this.onLoadPackageList()
      },
      onLoadPackageList(page, params = {}) {
        this.packageLoading = true;
        const values = {
          ...params,
          goodsId: this.goodsId,
        };
        getPackageList(
          1,
          100,
          values
        ).then((res) => {
          const data = res.data.data;
          this.goodsPackageList = data.records;
          this.packageLoading = false;
        });
      },
      submitPackage() {
        this.goodsPackageList.map(goodsPackage => {
          goodsPackage.goodsId = this.goodsId
        })
        submitPackage(this.goodsPackageList, this.goodsId).then(() => {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.dialogPackageVisible = false
        }, error => {
          window.console.log(error);
        });
      },


      rowSave(row, done, loading) {
        this.cleanPicTimer()
        row.categoryId = row.categoryId.join(",");
        add(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowUpdate(row, index, done, loading) {
        this.cleanPicTimer()
        row.categoryId = row.categoryId.join(",");
        update(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        this.setPicTimer()
        this.temPictureNameArray = this.form.pictureUrl ? this.form.pictureUrl.split(',') : []

        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
            if(this.form.hasOwnProperty("categoryId")){
              this.form.categoryId = (this.form.categoryId === undefined || this.form.categoryId === '')
              ? [] : this.form.categoryId.split(",");
            }
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
        getCategoryList().then(res => {
          const column = this.findObject(this.option.column, "categoryId");
          column.dicData = res.data.data;
        });
      }
    }
  };
</script>

<style>
</style>
